package org.jeefb.web.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.jeefb.common.ServiceResult;
import org.jeefb.modules.sys.contants.SystemCachedContants;
import org.jeefb.modules.sys.service.CachedService;
import org.jeefb.modules.sys.service.SystemService;
import org.jeefb.modules.sys.vo.MenuTreeVO;
import org.jeefb.web.utils.JeeFBUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

/**
 * 权限拦截器
 * 
 * @author
 * 
 */
public class AuthInterceptor implements HandlerInterceptor {
	private static final Logger logger = Logger.getLogger(AuthInterceptor.class);
	@Autowired
	private CachedService cachedService;
	@Autowired
	private SystemService systemService;

	/**
	 * 在controller后拦截
	 */
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object,
			Exception exception) throws Exception {
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
			ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 在controller前拦截
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		HttpSession session = request.getSession();
		String path = request.getContextPath();
		// 判断是否登录
		try {
			ServiceResult<String> result = cachedService.getCachedObjectByKey(SystemCachedContants.ADMIN_USER_SESSION + session.getId());
			if (result.getSuccess() && result.getResult() != null) {
				// 判断是否有菜单权限
				String requestPath = JeeFBUtils.getRequestPath(request);// 用户访问的资源地址
				if (!hasMenuAuth(requestPath, session.getId())) {
					response.sendRedirect("error/noAuth");
					return false;
				} else {
					return true;
				}
			} else {
				// 未登录则跳转至首页进行重新登录
				response.sendRedirect(path+"/login");
				return false;
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			response.sendRedirect(path+"/error/500");
			return false;
		}

	}

	/**
	 * 判断用户是否有菜单访问权限
	 * 
	 * @param request
	 * @return
	 */
	private boolean hasMenuAuth(String requestPath, String sessionId) {
		ServiceResult<Boolean>	hasMenuUrl = systemService.getFunctionByUrl(requestPath);
		if(hasMenuUrl.getSuccess() && hasMenuUrl.getResult()){
			// 是否是功能表中管理的url
			ServiceResult<String> result = cachedService.getCachedObjectByKey(SystemCachedContants.ADMIN_FUNCTION_SESSION + sessionId);
			if (result.getSuccess() && result.getResult() != null) {
				List<MenuTreeVO> menus = JSON.parseArray(result.getResult(), MenuTreeVO.class);
				for (MenuTreeVO menuTreeVO : menus) {
				   if(menuTreeVO.getFunctionUrl() != null && requestPath !=null) {
						if (menuTreeVO.getFunctionUrl().contains(requestPath)) {
							return true;
						}
					}
				}
			}
			return false;
		} else {
			return true;
		}

	}

}
